package com.lingnan.blog.controller;

import com.lingnan.blog.entity.Comment;
import com.lingnan.blog.entity.Result;
import com.lingnan.blog.service.ArticleService;
import com.lingnan.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private ArticleService articleService;


    @PostMapping("/save")
    @ResponseBody
    public Result saveCommentData(Comment comment) {
        try {
            Result result = new Result();
            Comment userComment = commentService.findByUIdAndAId(comment.getUId(), comment.getAId());
            //如果查出来的数据不为空
            if (StringUtils.isEmpty(userComment)) {
                //添加数据
                commentService.save(comment);
                //更新文章评论数
                articleService.updateComments(comment.getAId());
                result.setFlag(true);
            } else {
                //直接返回错误
                result.setFlag(false);
                result.setMsg("评论失败，你已经评论过当前文章！");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
